using System;

namespace Sedge.Core.App
{
    public class SuiteFinderOptions
    {
        public string SuiteFile { get; set; }
        public string AppName { get; set; }
        public string RootFolder { get; set; }

        public SuiteFinderOptions()
        {
            AppName = String.Empty;
            SuiteFile = String.Empty;
            RootFolder = String.Empty;
        }

        public static SuiteFinderOptions Compose(CommandLineParams clp, AppConfiguration appConfiguration)
        {
            SuiteFinderOptions options = new SuiteFinderOptions {SuiteFile = clp.Suite, AppName = clp.App, RootFolder = appConfiguration.DefaultFolder};

            if (String.IsNullOrEmpty(options.SuiteFile))
            {
                if (!GetDefaultSuite(options, appConfiguration))
                {
                    GetSuiteFromFolders(options, appConfiguration);
                }
            }

            if (!String.IsNullOrEmpty(options.SuiteFile))
            {
                if (!Services.FileSystem.File.Exists(options.SuiteFile))
                    options.SuiteFile = String.Empty;
            }

            return options;
        }

        private static bool GetDefaultSuite(SuiteFinderOptions options, AppConfiguration appConfiguration)
        {
            bool suiteFound = false;
            if (!String.IsNullOrEmpty(appConfiguration.DefaultApplication))
            {
                options.AppName = appConfiguration.DefaultApplication;
            }

            if (!String.IsNullOrEmpty(appConfiguration.DefaultSuite) && Services.FileSystem.File.Exists(appConfiguration.DefaultSuite))
            {
                options.SuiteFile = appConfiguration.DefaultSuite;
                suiteFound = true;
            }
            return suiteFound;
        }

        private static void GetSuiteFromFolders(SuiteFinderOptions options, AppConfiguration appConfiguration)
        {
            string[] suites = SuiteFinder.SearchForSuite(appConfiguration.SearchFolder, true);
            if (suites.Length == 0)
            {
                suites = SuiteFinder.SearchForSuite(appConfiguration.DefaultFolder, true);
            }
            if (suites.Length != 0)
                options.SuiteFile = suites[0];
        }

    }
}